'use strict';

const Grid = require('gridfs-stream');
const mongo = require('mongodb');
const fs = require('fs');
const qiniu = require('yi-qiniu');

const  middleware = (req, res, next)=>{
  let id=req.params.id;
    req.mongo.collection('file').findOne({_id:id},(e,r)=>{
        if (e) return res.err.mongoError(e);

        if(!r)
          return res.err.nothingToDelete();

        req.context = req.context || {};
        req.context.delFile = r;
        next();
    });
};

const handler = (req, res, next)=>{

  let delFile = req.context.delFile;
  if(delFile.static===1){   //静态资源
    fs.unlink(delFile.url,()=>{
        req.mongo.collection('file').deleteOne({_id:req.params.id}, (e,r)=>{
            res.reply({code:0,message:'删除成功',data:delFile})
        } );
    });
  }else if (delFile.static===2){  //七牛云资源
    qiniu.removeFile(delFile._id.toString()+'/'+delFile.filename,(e1,r1)=>{
        req.mongo.collection('file').deleteOne({_id:req.params.id}, (e,r)=>{
            res.reply({code:0,message:'删除成功',data:delFile})
        } );
    });

  }else { //其它默认为数据库资源
      const gfs = Grid(req.mongo, mongo);
      gfs.remove({_id:req.params.id}, function (err) {
          if (err) return res.err.mongoError(err);
          req.mongo.collection('file').deleteOne({_id:req.params.id}, (e,r)=>{
              res.reply({code:0,message:'删除成功',data:delFile})
          } );
      });
  }

};

module.exports = {
    open:false,
    description:'删除上传信息',
    middleware: middleware,
  handler: handler
};

